﻿using MediatR;
using PublicCommon;
using T_settlement.Domain;
using T_settlement.Infrastructure.Interfacec;
using T_settlement.Read.API.Application.Command.InvoiceCommand;

namespace T_settlement.Read.API.Application.CommandHandlers.InvoiceCommandHandlers
{
    public class GetInvoiceCommandHandlers : IRequestHandler<GetInvoiceCommand, PageResult<Invoice>>
    {
        private readonly InvoiceRepository invoiceRepositorys;

        public GetInvoiceCommandHandlers(InvoiceRepository invoiceRepositorys)
        {
            this.invoiceRepositorys = invoiceRepositorys;
        }

        public async Task<PageResult<Invoice>> Handle(GetInvoiceCommand request, CancellationToken cancellationToken)
        {
            var list = invoiceRepositorys.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();

            if (!string.IsNullOrEmpty(request.Ticket))
            {
                list = list.Where(x => x.Ticket.Contains(request.Ticket));
            }

            if (request.InvoiceType != 0 && request.InvoiceType != null)
            {
                list = list.Where(x => x.InvoiceType == request.InvoiceType);
            }

            if (!string.IsNullOrEmpty(Convert.ToString(request.Invoicetime)))
            {
                list = list.Where(x => x.Invoicetime == request.Invoicetime);
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.OrderByDescending(x=>x.InvoiceId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Invoice>
            {
                PageCount = pageCount,
                TotalCount = totalCount,
                List = res
            };
        }
    }
}
